package com.prevpn.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.prevpn.api.RoleApi;
import com.prevpn.common.CommonResponse;
import com.prevpn.common.CommonUtil;
import com.prevpn.dto.RoleAssignResourceDTO;
import com.prevpn.dto.RoleCreateDTO;
import com.prevpn.service.RoleService;
import com.prevpn.vo.RoleDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleApi roleApi;

    // 创建角色
    @Override
    public CommonResponse<Map<String, Object>> createRole(RoleCreateDTO dto) {
        CommonResponse<Map<String, Object>> resp = new CommonResponse<>();

        // ✅ 参数校验
        if (dto == null || StrUtil.isBlank(dto.getDirectoryDomain()) || StrUtil.isBlank(dto.getName())) {
            resp.setCode("400");
            resp.setMsg("参数不完整：directoryDomain 与 name 必须填写");
            return resp;
        }

        // ✅ 调用 API 创建角色
        CommonResponse<Map<String, Object>> apiResp = roleApi.createRole(
                dto.getDirectoryDomain(),
                dto.getName(),
                dto.getDescription(),
                dto.getExternalId()
        );

        // ✅ 返回结果
        resp.setCode(apiResp.getCode());
        resp.setMsg(apiResp.getMsg());
        resp.setTraceId(apiResp.getTraceId());
        resp.setData(apiResp.getData());
        return resp;
    }

    // 查询角色
    @Override
    public CommonResponse<RoleDetailVO> queryRoleByName(String directoryDomain, String name, Integer type) {
        CommonResponse<Map<String, Object>> apiResp =
                roleApi.queryRoleByName(directoryDomain, name, type);

        CommonResponse<RoleDetailVO> resp = new CommonResponse<>();
        resp.setCode(apiResp.getCode());
        resp.setMsg(apiResp.getMsg());
        resp.setTraceId(apiResp.getTraceId());

        if (!"OK".equalsIgnoreCase(apiResp.getCode())) {
            return resp;
        }

        RoleDetailVO detail = JSONUtil.toBean(
                JSONUtil.toJsonStr(apiResp.getData()),
                RoleDetailVO.class
        );
        resp.setData(detail);
        return resp;
    }

    // 角色分配资源
    //private static final String ASSIGN_RESOURCE_PATH = "/api/v3/role/assignResourceByName";
    //
    //public CommonResponse<Object> assignResourceByName(RoleAssignResourceDTO dto) {
    //    String json = JSONUtil.toJsonStr(dto);
    //    String response = CommonUtil.openApiPostRequest(ASSIGN_RESOURCE_PATH, json);
    //    return JSONUtil.toBean(response, CommonResponse.class);
    //}
    @Override
    public CommonResponse<Object> assignResourceByName(RoleAssignResourceDTO dto) {
        // ✅ 参数序列化
        String json = JSONUtil.toJsonStr(dto);

        // ✅ 调用 API 层
        CommonResponse<Map<String, Object>> apiResp = roleApi.assignResourceByName(json);

        // ✅ 返回统一结构
        CommonResponse<Object> resp = new CommonResponse<>();
        resp.setCode(apiResp.getCode());
        resp.setMsg(apiResp.getMsg());
        resp.setTraceId(apiResp.getTraceId());
        resp.setData(apiResp.getData());
        return resp;
    }

    /**
     * 查询角色列表（分页 + 模糊搜索）
     */
    @Override
    public CommonResponse<Map<String, Object>> queryRoleList(Map<String, Object> body) {
        CommonResponse<Map<String, Object>> resp = new CommonResponse<>();

        // 1️⃣ 参数校验
        if (body == null || !body.containsKey("directoryDomain")) {
            resp.setCode("400");
            resp.setMsg("参数不完整：directoryDomain 必须填写");
            return resp;
        }

        // 2️⃣ 默认分页参数
        int pageSize = parseIntOrDefault(body.get("pageSize"), 10);
        int pageIndex = parseIntOrDefault(body.get("pageIndex"), 1);
        body.put("pageSize", pageSize);
        body.put("pageIndex", pageIndex);

        // 3️⃣ 模糊匹配参数（可选）
        String fuzzyMatch = body.containsKey("fuzzyMatch") ? body.get("fuzzyMatch").toString() : "";
        if (StrUtil.isNotBlank(fuzzyMatch)) {
            body.put("fuzzyMatch", fuzzyMatch);
        }

        // 4️⃣ 调用 OpenAPI
        return roleApi.queryRoleList(body);
    }

    private int parseIntOrDefault(Object value, int defaultVal) {
        if (value == null) return defaultVal;
        if (value instanceof Number) return ((Number) value).intValue();
        try {
            return Integer.parseInt(value.toString());
        } catch (Exception e) {
            return defaultVal;
        }
    }

    /**
     * 批量删除角色（基于名称）
     */
    @Override
    public CommonResponse<Map<String, Object>> bulkDeleteByNameList(Map<String, Object> body) {
        CommonResponse<Map<String, Object>> resp = new CommonResponse<>();

        if (body == null) {
            resp.setCode("400");
            resp.setMsg("参数不能为空");
            return resp;
        }

        String directoryDomain = (String) body.get("directoryDomain");
        List<String> nameList = (List<String>) body.get("nameList");

        if (StrUtil.isBlank(directoryDomain) || nameList == null || nameList.isEmpty()) {
            resp.setCode("400");
            resp.setMsg("参数不完整：directoryDomain 和 nameList 必填");
            return resp;
        }

        // ✅ 调用 OpenAPI
        String jsonBody = JSONUtil.toJsonStr(body);
        CommonResponse<Map<String, Object>> apiResp = roleApi.bulkDeleteByNameList(jsonBody);

        // ✅ 返回统一格式
        resp.setCode(apiResp.getCode());
        resp.setMsg(apiResp.getMsg());
        resp.setData(apiResp.getData());
        resp.setTraceId(apiResp.getTraceId());
        return resp;
    }

    /**
     * 编辑角色（基于名称）
     */
    @Override
    public CommonResponse<Map<String, Object>> updateRoleByName(Map<String, Object> body) {
        CommonResponse<Map<String, Object>> resp = new CommonResponse<>();

        if (body == null) {
            resp.setCode("400");
            resp.setData(null);
            resp.setMsg("参数不能为空");
            return resp;
        }

        String directoryDomain = (String) body.get("directoryDomain");
        String name = (String) body.get("name");

        if (StrUtil.isBlank(directoryDomain) || StrUtil.isBlank(name)) {
            resp.setCode("400");
            resp.setData(null);
            resp.setMsg("参数不完整：directoryDomain 和 name 必填");
            return resp;
        }


        return roleApi.updateRoleByName(JSONUtil.toJsonStr(body));
    }

}
